const fs = require('fs')
const path = require('path')
const sourceMap = require('source-map')
const ora = require('ora')
const chalk = require('chalk')
const log = console.log
let sourcesPathMap = {}
function fixPath (filepath) {
  return filepath.replace(/\.[\.\/]+/g, '')
}

module.exports = {
  async sourceMap (ages) {
    log('')
    const spinner = ora('代码分析中，请稍后...').start()
    spinner.color = 'yellow'
    let root = process.cwd()
    let sourcemapFilePath = path.join(root, ages.fileName)
    if (!fs.existsSync(sourcemapFilePath)) {
      spinner.text = '文件不存在,请选择正确的文件'
      spinner.fail()
      log('')
      log(`${chalk.yellow('  输入的文件: ' + ages.fileName)}`)
      log('')
      return
    }
    let sourceMapContent = fs.readFileSync(sourcemapFilePath, 'utf-8')
    let fileObj = JSON.parse(sourceMapContent)
    let sources = fileObj.sources

    sources.map(item => {
      sourcesPathMap[fixPath(item)] = item
    })

    let findPos = {
      line: Number(ages.line),
      column: Number(ages.column),
    }

    try {
      let consumer = await new sourceMap.SourceMapConsumer(sourceMapContent)
      let result = consumer.originalPositionFor(findPos)

      let originSource = sourcesPathMap[result.source]

      let sourcesContent = fileObj.sourcesContent[sources.indexOf(originSource)]
      let sourcesContentArr = sourcesContent.split('\n')
      result.sourcesContentMap = sourcesContentArr
      spinner.text = '分析完毕'
      spinner.succeed()
      log('')
      log(`${chalk.yellow('  输入的文件: ' + ages.fileName)}`)
      log(`${chalk.yellow('  输入的行: ' + ages.line)}`)
      log(`${chalk.yellow('  输入的列: ' + ages.column)}`)
      log('')
      log(`${chalk.green('  分析结果如下: ')}`)
      log('')
      // 防止越界
      let line = result.line
      if (line < 4) {
        let x = 4 - line
        for (let i = 0; i < x; i++) {
          result.sourcesContentMap.unshift('防止越界替补空数据')
        }
        line = 4
      }
      result.sourcesContentMap = result.sourcesContentMap.slice(line - 4, line + 3)
      result.sourcesContentMap.forEach((element, i) => {
        if (i === 3) {
          log(`${chalk.red('  ' + element)}`)
        } else {
          log(`${chalk.green('  ' + element)}`)
        }
      })
      log('')
      log(`${chalk.green('  错误对应的源码信息:')}`)
      log('')
      console.log(result)
    } catch (error) {
      spinner.text = '分析失败，请检查文件是否正确，行列信息是否正确'
      spinner.fail()
      log('')
      log(`${chalk.yellow('  输入的文件: ' + ages.fileName)}`)
      log(`${chalk.yellow('  输入的行: ' + ages.line)}`)
      log(`${chalk.yellow('  输入的列: ' + ages.column)}`)
    }
  },
}
